<?php
/**
 * Created by PhpStorm.
 * User: woody
 * Date: 17-2-16
 * Time: 下午10:46
 */

namespace App\Http\Controllers\Admin;
use DB;
use App\Models\PersonInfo;
use Illuminate\Http\Request;

use App\Models\Pointforapi;

class PersonInfoController extends AdminController {

    public function __construct()
    {
        parent::__construct();
        $this->_response['_active']['_model']       = 'personInfo';
        $this->_response['_active']['_action']      = '';
        $this->_response['_title']                  = '小一农货-个人中心管理';
    }
    public function index(Request $request){
        $page = $request->get('page', 1);
        $search = $request->all();
        $this->_response['_active']['_action']      = 'list';
        $PersonInfoModel = new PersonInfo();
        $data = $PersonInfoModel->getData($search, $page, 20);
        $this->_response['personInfo'] = $data;
        $this->_response['personInfo']['pageData']['page'] = $page;
        $this->_response['personInfo']['pageData']['pageHtml'] = self::getPageHtml($page , $this->_response['personInfo']['pageData']['lastPage'] , '/admin/personInfo?');
        return view('admin.personInfo.list', $this->_response);
    }

    public function getpoint(Request $request){
        $page = $request->get('page', 1);
        $search = $request->all();
        $this->_response['_active']['_action']      = 'listpoint';

        $PersonInfoModel = new PersonInfo();
        $data = $PersonInfoModel->getDatapoint($search, $page, 20);
        $this->_response['personInfo'] = $data;
        $this->_response['personInfo']['pageData']['page'] = $page;
        $this->_response['personInfo']['pageData']['pageHtml'] = self::getPageHtml($page , $this->_response['personInfo']['pageData']['lastPage'] , '/admin/personInfo/point?');

        return view('admin.personInfo.listpoint', $this->_response);
    }

    public function add(){
        $this->_response['_active']['_action']      = 'add';
        return view('admin.personInfo.add', $this->_response);
    }


    public function edit($id){
        $this->_response['personInfo'] = PersonInfo::where('id', $id)->first();
        return view('admin.personInfo.edit', $this->_response);
    }

    public function doedit(\App\Http\Requests\PersonInfo $request){
        $data = $request->all();
        $pointtime=strtotime($data['point_time']);
        $curent=date('Y-m-d H:i:s',time());
        $curent=strtotime($curent);

        $point_time= $pointtime-$curent;

        $PersonInfoModel = new PersonInfo();
   //将添加的积分转为整形
        $addpoints = intval($data['addpoints']);
        $pointnumber = intval($data['pointnumber']);
        $data['partner_ratio'] = floatval($data['partner_ratio']);
        $data['vip_ratio'] = floatval($data['vip_ratio']);
    //返分次数
        $num=$addpoints/$pointnumber;
        $saveData = [
            'totalPoints' => $data['points'],
            'updated_at' => date('Y-m-d H:i:s', time())
        ];
   //查询该用户的信息
        $user=PersonInfo::where('id', $data['id'])->first();
   //查询上级的信息
        $vuser=PersonInfo::where('id', $user['inviter_id'])->first();
   //如果直属上级存在且为合伙人则增加该积分的比率
        if(!empty($user['inviter_id'])&&$vuser['user_level']==1){
            $vpresntPoints=intval($vuser['totalPoints']);
    //上级总积分
            $vpoints=$addpoints*$data['partner_ratio']+$vpresntPoints;

//            $vuser=PersonInfo::where('id', $user['inviter_id'])->first();
            $vsaveData=[
                'totalPoints' => $vpoints,
                'updated_at' => date('Y-m-d H:i:s', time())
            ];

           // $PersonInfoModel->setData($user['inviter_id'],$vsaveData);
        }
    //如果上级存在且为vip则增加该积分的比率
                if(!empty($user['inviter_id'])&&$vuser['user_level']==0){
     //上级总积分
                    $ppresntPoints=intval($vuser['totalPoints']);
                    $ppoints=$addpoints*$data['vip_ratio']+$ppresntPoints;
                   // $puser=PersonInfo::where('id', $user['inviter_id'])->first();
                    $psaveData=[
                        'totalPoints' => $ppoints,
                        'updated_at' => date('Y-m-d H:i:s', time())
                    ];
                  //  $PersonInfoModel->setData($user['inviter_id'],$psaveData);
                }

        if($PersonInfoModel->setData($data['id'],$saveData)){
            ignore_user_abort(TRUE);// 设定关闭浏览器也执行程序
            set_time_limit(0);      // 设定响应时间不限制，默认为30秒

            $count = 0;
            while (TRUE)
            {
                if($count==0){
                    sleep($point_time);           // 每隔指定时间执行一次
                }else{
                    sleep(3600*24);           // 每隔指定时间执行一次
                }

                DB::beginTransaction();
                try {
                    //查询该用户的信息
                    $user=PersonInfo::where('id', $data['id'])->first();
                    //查询上级的信息
                    $vuser=PersonInfo::where('id', $user['inviter_id'])->first();
                    $presntPoints=intval($user['presentPoints']);
                    $saveData = [
                        'presentPoints' => $pointnumber+$presntPoints,
                        'updated_at' => date('Y-m-d H:i:s', time()),
                        'totalPoints' =>$user['totalPoints']-$pointnumber,
                    ];
                    $PersonInfoModel->setData($data['id'],$saveData);
 //var_dump($saveData);
                    //如果直属上级为合伙人则返该积分的比率
                    if(!empty($user['inviter_id'])&&$vuser['user_level']==1){
                        $vpresntPoints=intval($vuser['presentPoints']);
                        //上级现有积分
                        $vpoints=$pointnumber*$data['partner_ratio']+$vpresntPoints;
                        $vsaveData=[
                            'presentPoints' => $vpoints,
                            'updated_at' => date('Y-m-d H:i:s', time()),
                        ];
                       // var_dump($vsaveData);
                        $PersonInfoModel->setData($user['inviter_id'],$vsaveData);
                    }
                        //如果上级为vip则返该积分的比率
                        if(!empty($user['inviter_id'])&&$vuser['user_level']==0){
                            //上级现有积分
                            $ppresntPoints=intval($vuser['presentPoints']);
                            $ppoints=$pointnumber*$data['vip_ratio']+$ppresntPoints;
                            $psaveData=[
                                'presentPoints' => $ppoints,
                                'updated_at' => date('Y-m-d H:i:s', time())
                            ];
                           // var_dump($psaveData);
                            $PersonInfoModel->setData($user['inviter_id'],$psaveData);
                        }

                    DB::commit();

                } catch (\Exception $error) {
                    DB::rollBack();
                    \Log::debug($error);

                }
            catch (\Exception $exception){
                \Log::error($exception);
            }
               $count++;
                // 设定定时任务终止条件
                if ($count>=$num)
                {
                    break;
                }
            }
            return response()->json(['code' => 0, 'msg' => '修改成功']);
        }else{
            return response()->json(['code' => -1, 'msg' => '修改失败']);
        }

    }

    //返现编辑

    public function editcash(Request $request){
        $data=$request->all();
        $id=$data['id'];
        $user_id=$data['user_id'];
        $user=Pointforapi::where('id', $id)->first();
        $userinfo=PersonInfo::where('id', $user['user_id'])->first();
//        print_r($data);
//        exit;
        $setData =[
            'iscashback'=>1,
            'updated_at' => date('Y-m-d H:i:s', time())
        ];
        $PersonInfoModel = new PersonInfo();
   //返现成功后发送模板消息
        if($PersonInfoModel->setpoints($id,$setData)){

            $appId ='wxdcc84c7bc4f6bd9f';
            $openId=$userinfo['wx_openid'];
            $tempid='Ypfvy6MYKvhOMHIFR7R4tKqH5otNEYgxTB7Ub4VMpMw';
            $data= array(
                "first" => array(
                    "value"=>"您的积分返现已到账",
                    "color"=>"#173177"
                ),
                "order"=>array(
                    "value"=>$user['order'], //传的变量
                    "color"=>"#173177"
                ),
                "money"=> array(
                    "value"=>$user['money'],//到账金额
                    "color"=>"#173177"
                ),
                "remark"=> array(
                    "value"=>"点击查看详情",
                    "color"=>"#173177"
                ),
          );
            $url   ="";
            $this->sendTempMsg($appId, $openId, $tempid, $data, $url);
        }

    }

    public function delete($id){

        $PersonInfoModel = new PersonInfo();
        $data=[
            'deleted_at'=>date('Y-m-d H:i:s',time())
        ];
        if($PersonInfoModel->delData($id,$data)){
            return response()->json(['code' => 0, 'msg' => '删除成功']);

        }else{
            return response()->json(['code' => -1, 'msg' => '删除失败']);
        }
    }


}